package com.unknownman.block.controller.open;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lianziyou.chain.common.api.CommonPage;
import com.lianziyou.chain.common.api.CommonParam;
import com.unknownman.block.mapper.TTokenTransRecord;
import com.unknownman.block.service.TTokenTransRecordService;
import org.cloud.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * erc20转账记录
 */
@RestController
@RequestMapping(value = "/erc20/transferRecord")
public class Erc20TransferRecordContract {
    @Autowired
    private TTokenTransRecordService tokenTransRecordService;

    @RequestMapping(method = RequestMethod.POST, value = "/list")
    public CommonPage<TTokenTransRecord> list(@RequestBody Map<String, Object> conditions,
                                              CommonParam pageParam) {
        List<String> froms = (List) conditions.getOrDefault("froms", Arrays.asList());
        List<String> tos = (List) conditions.getOrDefault("tos", Arrays.asList());
        List<String> contracts = (List) conditions.getOrDefault("contracts", Arrays.asList());
        if (CollectionUtil.single().isEmpty(froms) || CollectionUtil.single().isEmpty(tos) || CollectionUtil.single().isEmpty(contracts)) {
            return null;
        }

        QueryWrapper<TTokenTransRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .and(
                        qw -> {
                            for (String contract : contracts) {
                                if (!StringUtils.isEmpty(contract)) {
                                    qw.eq(TTokenTransRecord::getTokenAddress, contract).or();
                                }
                            }
                        })
                .and(
                        qw -> {
                            for (String from : froms) {
                                if (!StringUtils.isEmpty(from)) {
                                    qw.eq(TTokenTransRecord::getFromAddress, from).or();
                                }
                            }
                        })
                .and(
                        qw -> {
                            for (String to : tos) {
                                if (!StringUtils.isEmpty(to)) {
                                    qw.eq(TTokenTransRecord::getToAddress, to).or();
                                }
                            }
                        });
        CommonPage<TTokenTransRecord> list = tokenTransRecordService.findListByPage(pageParam.getPage(), pageParam.getLimit(), "block_timestamp desc", queryWrapper);
        return list;
    }
}
